package johnkkk.com.obj;

import android.opengl.GLES20;
import android.opengl.GLES30;
import android.os.Build;
import android.support.annotation.RequiresApi;

import com.graphics.element.AbsSceneNode;
import com.system.Shader;
import com.tools.SizeOf;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

/**
 * @Author: clm
 * @Date: 2018-10-27
 */

public class GeoObj extends AbsSceneNode {
    private int mGeoObjVAO[];
    private Shader mShader;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public GeoObj(String name) {
        super(name);
        //vertices
        float[] vertex = {
            -5.0f, -5.0f, -10.0f,
            5.0f, -5.0f, -10.0f,
            0.0f, 5.0f, -10.0f,
        };
        FloatBuffer fb = ByteBuffer.allocateDirect(vertex.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        fb.put(vertex).position(0);
        //shader
        mShader = new Shader("test_vs.glsl", "test_gs.glsl", "test_fs.glsl");
        //mShader = new Shader("test_vs.glsl", "test_fs.glsl");
        mGeoObjVAO = new int[1];
        int[] vbo = new int[1];
        GLES30.glGenBuffers(1, vbo, 0);
        GLES30.glGenVertexArrays(1, mGeoObjVAO, 0);
        //绑定uniform缓存
        GLES30.glUseProgram(mShader.mShaderProgram);
        GLES30.glUniformBlockBinding(mShader.mShaderProgram, GLES30.glGetUniformBlockIndex(mShader.mShaderProgram, "MATRIX"), 0x001);
        GLES30.glUseProgram(0);

        GLES30.glBindVertexArray(mGeoObjVAO[0]);
        GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vbo[0]);
        GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER, fb.limit() * 4, fb, GLES30.GL_STATIC_DRAW);
        GLES30.glVertexAttribPointer(0x001, 3, GLES30.GL_FLOAT, false, 3 * SizeOf.S_FLOAT_SIZE, 0);
        GLES30.glEnableVertexAttribArray(0x001);
        GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0);
        GLES30.glBindVertexArray(0);
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void render(float exTime) {
        //super.render(exTime);
        //尽管编译使用的是GLSL320版本编译,但是渲染时调用GLES30接口任然可以渲染,因为着色器编译跟渲染接口是分开的
        //为了向后兼容最好统一使用gles32接口渲染
        GLES30.glUseProgram(mShader.mShaderProgram);
        GLES30.glBindVertexArray(mGeoObjVAO[0]);
        GLES30.glDrawArrays(GLES30.GL_POINTS, 0, 3);
        GLES30.glBindVertexArray(0);
        GLES30.glUseProgram(0);
    }

    @Override
    public void update(float exTime) {
        super.update(exTime);
    }
}
